import React, { useState } from 'react';
import { 
  Form, Input, Select, DatePicker, Button, 
  message, Card, Space
} from 'antd';
import { 
  CloseCircleOutlined, SaveOutlined, 
  HomeOutlined 
} from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import RefundsService from '../../services/RefundsService';
import '../components.css';

const { Option } = Select;

export default function AddRefund() {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values) => {
    try {
      setLoading(true);
      // 准备提交数据
      const submitData = {
        ...values,
        refundDate: values.refundDate.format('YYYY-MM-DD'), // 格式化日期
        refundAmount: parseFloat(values.refundAmount),     // 转换金额为数字
      };
      // 调用API
      const response = await RefundsService.createRefund(submitData);
      if (response.status === 200 || response.status === 201) {
        message.success('退款添加成功！');
        navigate('/refundlist');
      } else {
        throw new Error(response.data?.message || '添加失败');
      }
    } catch (error) {
      console.error('添加退款失败:', error);
      message.error(error.message || '添加退款失败，请重试！');
    } finally {
      setLoading(false);
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('提交失败:', errorInfo);
    message.error('表单验证失败，请检查输入！');
  };

  return (
    <Card bordered={false} className="add-refund-card" headStyle={{ textAlign: 'center' }} style={{ paddingBottom: '30px' }}>
      <div className="title" style={{ paddingBottom: '30px' }}>添加退款</div>
      <Form form={form} name="add-refund" 
        onFinish={onFinish} onFinishFailed={onFinishFailed}
        labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}
        initialValues={{ approvalStatus: 'pending', refundMethod: 'bank'}}>
        <Form.Item label="退款编号" name="refundNumber"
          rules={[{ required: true, message: '请输入退款编号!' },
          { pattern: /^[A-Za-z0-9-]+$/, message: '编号只能包含字母、数字和横线' }]}>
          <Input placeholder="如：RF-20230001" />
        </Form.Item>

        <Form.Item label="关联客户" name="relatedCustomer"
          rules={[{ required: true, message: '请输入关联客户!' }]}>
          <Input placeholder="客户名称或编号" />
        </Form.Item>

        <Form.Item label="关联订单" name="relatedOrder"
          rules={[{ required: true, message: '请输入关联订单!' }]}>
          <Input placeholder="订单编号" />
        </Form.Item>

        <Form.Item label="退款金额" name="refundAmount"
          rules={[{ required: true, message: '请输入退款金额!' },
          { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效金额（如：100 或 100.50）' }]}>
          <Input prefix="¥" placeholder="0.00" />
        </Form.Item>

        <Form.Item label="退款方式" name="refundMethod"
          rules={[{ required: true, message: '请选择退款方式!' }]}>
          <Select>
            <Option value="bank">银行转账</Option>
            <Option value="alipay">支付宝</Option>
            <Option value="wechat">微信支付</Option>
            <Option value="cash">现金</Option>
          </Select>
        </Form.Item>

        <Form.Item label="退款日期" name="refundDate"
          rules={[{ required: true, message: '请选择退款日期!' }]}>
          <DatePicker style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item label="审批状态" name="approvalStatus"
          rules={[{ required: true, message: '请选择审批状态!' }]}>
          <Select>
            <Option value="pending">待审批</Option>
            <Option value="approved">已通过</Option>
            <Option value="denied">被否决</Option>
            <Option value="rejected">被驳回</Option>
            <Option value="revoked">已撤销</Option>
          </Select>
        </Form.Item>

        <Form.Item label="负责人员" name="responsiblePerson"
          rules={[{ required: true, message: '请输入负责人员!' }]}>
          <Input placeholder="经办人姓名" suffix={<HomeOutlined />} />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SaveOutlined />} loading={loading}>提交</Button>
            <Button danger icon={<CloseCircleOutlined />} onClick={() => navigate('/refundlist')}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}